<?php
/**
 * 服务模块
 *
 * User: Jay
 * Date: 2018/8/8
 */

namespace AdminBundle\Controller;


use AdminBundle\RBAC\Item;
use AdminBundle\Entity\Admin;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class AuthAssignmentController extends AdminController
{
    public function listAction()
    {
        $r = $this->inlet($this->getParameter('return_page'), true);
        if ($r !== true) {
            return $r;
        }

        $this->adminStrategy->setUrlMark('assignments');
        $sql = 'SELECT a.id, a.name, a.account, a.is_del, GROUP_CONCAT(description separator "、") AS roles '
            . 'FROM admin a '
            . 'LEFT JOIN `auth_assignment` aa on a.id = aa.user_id '
            . 'LEFT JOIN auth_item ai ON ai.name = aa.item_name '
            . 'WHERE a.is_del = 0 '
            . 'GROUP BY a.id ';
        $users = self::$conn->fetchAll(
            $this->get('unicorn.sql')->sqlMosaicLimit($sql)
        );

        $AdminController = new AdminController($this->container);


        foreach ($users as $key => $value) {
            $users[$key]['admin'] = $AdminController->isSuperAdmin($value['id']);
        }

        $total = self::$conn->fetchColumn('SELECT COUNT(*) FROM admin');

        return $this->render('@Admin/admin/Authorization/assignment-list.html.twig', array(
                'info' => $users,
                'paging' => $this->adminStrategy->paging($total)['paging']
            )
        );
    }

    public function showAction($id)
    {
        $r = $this->inlet($this->getParameter('return_page'), true);
        if ($r !== true) {
            return $r;
        }

        $this->adminStrategy->setUrlMark('assignments');

        $admin = $this->getDoctrine()->getRepository(Admin::class)->find($id);
        if (!$admin) {
            return $this->redirectToRoute('admin_assignment_list');
        }

        return $this->render('@Admin/admin/Authorization/assignment-form.html.twig',
            array(
                'admin' => $admin
            )
        );
    }

    public function assignAction(Request $request)
    {
        $r = $this->inlet($this->getParameter('return_data'), true);
        if ($r !== true) {
            return $r;
        }

        $id = $request->request->get('id');
        $action = $request->request->get('action');
        $roles = $request->request->get('roles');

        $rbac = $this->get('rbac');

        $admin = $this->getDoctrine()->getRepository(Admin::class)->find($id);
        if (!$admin) {
            return $this->response('用户不存在', 1);
        }

        try {
            foreach ($roles as $roleName) {
                $role = $rbac->getRole($roleName);
                if (!$role) {
                    return $this->response('角色' . $roleName . '不存在', 1);
                }
                if ($action == 'assign') {
                    $rbac->assign($role, $id);
                } else {
                    $rbac->revoke($role, $id);
                }
            }
        } catch (\Exception $exception) {
            return $this->response($exception->getMessage(), 1);
        }

        return $this->response('操作成功', 0);
    }

    public function searchAction(Request $request)
    {
        $id = $request->query->get('id');
        $target = $request->query->get('target');

        $where = ' AND i.type = ' . Item::TYPE_ROLE;
        if ($request->query->get('term')) {
            $where .= ' AND i.description LIKE "%' . $request->query->get('term') . '%"';
        }

        $data = array();
        if ($target == 'avaliable') {
            // 检索可用的角色
            $data = $this->get('database_connection')
                ->fetchAll('SELECT name, description, type FROM auth_item i '
                    . 'WHERE NOT EXISTS(SELECT * FROM auth_assignment WHERE user_id = ? AND item_name = i.name) '
                    . $where . ' ORDER BY type ASC',
                    array($id)
                );
        } elseif ($target) {
            // 检索已分配的权限
            $data = $this->get('database_connection')
                ->fetchAll('SELECT name, description, type FROM auth_assignment a '
                    . 'LEFT JOIN auth_item i ON i.name = a.item_name '
                    . 'WHERE a.user_id = ? ' . $where . ' ORDER BY type ASC',
                    array($id)
                );
        }

        $result = array();
        foreach ($data as $v) {
            if ($v['type'] == Item::TYPE_ROLE) {
                $result['Roles'][$v['name']] = $v['description'];
            } else {
                $result['Permissions'][$v['name']] = $v['description'];
            }
        }

        return new JsonResponse($result);
    }
}
